package com.ruoyi.carShop.controller;

import com.ruoyi.carShop.service.LoginService;
import com.ruoyi.carShop.util.JwtUtil;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.system.api.domain.MerchantVerification;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author yang
 * @version 1.0
 * @data 2024/9/12 15:37
 */
@RestController
public class LoginController {

    @Autowired
    private RedisTemplate  redisTemplate;

    @Autowired
    private LoginService loginService;

    // 生成短信
    @RequestMapping("/createSms")
    public Map createSms(@RequestParam("phoneNumber") String phoneNumber) {
        System.out.println(phoneNumber);
        return loginService.createSms(phoneNumber);
    }

    // 登录
    @RequestMapping("/login")
    public AjaxResult login(String phoneNumber, String code) {

        String o = (String) redisTemplate.opsForValue().get(phoneNumber);
        System.out.println(o);
        if (o==null){
            return AjaxResult.error("验证码为空",null);
        }
        if( !o.equals(code) ) {
            return AjaxResult.error("验证码错误",null);
        }
        MerchantVerification merchant =  loginService.login(phoneNumber);
        if(merchant == null) {
            return AjaxResult.error("商家未注册",null);
        }
        String jwt = JwtUtil.createJWT(merchant.getMid().toString());
        redisTemplate.delete(phoneNumber);
        Map map = new HashMap();
        map.put("token",jwt);
        return AjaxResult.success("登录成功",map);

    }
}
